package demo12;

import java.io.*;
import java.util.Scanner;

public class test16 {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner scanner = new Scanner(System.in);
        //1.输入你要进行扫描的目录
        System.out.println("请输入你要扫描的目录：");
        String name = scanner.nextLine();
        File file = new File(name);
        //判断输入目录是否合法
        if(!file.isDirectory()) {
            System.out.println("输入的目录名不存在！！！");
            return;
        }
        System.out.println("请输入你要查找的字符");
        String word = scanner.nextLine();
        //2.可以开始扫描(递归)
        scanDir(file, word);
    }
    private static void scanDir(File file, String find) {
        File[] files = file.listFiles();
        for(File file1 : files) {
            if(file1.isDirectory()) {
                //是目录
                scanDir(file1, find);
            }else {
                //是文件
                //名称包含find
                if(isNameContain(file1, find)) {
                    System.out.println(file1.getAbsolutePath());
                }
                //内容是否包含
                if(isContentContain(file1, find)) {
                    System.out.println(file1.getAbsolutePath());
                    return;
                }
            }
        }
    }

    private static boolean isNameContain(File file1, String find) {
        String name = file1.getName();
        if(name.indexOf(find) != -1) {
            return true;
        }
        return false;
    }

    private static boolean isContentContain(File file1, String find) {
        try(InputStream inputStream = new FileInputStream(file1.getAbsolutePath())) {
            byte[] b = new byte[1024];
            int n = inputStream.read(b);
            String s = new String(b);
            if(s.equals(find)) {
                return true;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return false;
    }
}
